#!/bin/bash

BLACK="\033[1;90m"
RED="\033[1;91m"
GREEN="\033[1;92m"
YELLOW="\033[1;93m"
BLUE="\033[1;94m"
MAGENTA="\033[1;95m"
CYAN="\033[1;96m"
WHITE="\033[1;97m"
ENDCOLOR="\033[0m"

APPNAME=$(basename $0)
MODULE="random"
DEVICE="random"
MODE="644"
DEV_USER="pako"
DEV_GROUP="pako"
COUNTER=1
MINOR="0"


usage() {
	printf "Usage: %s <start|restart|stop> [module params]\n" $APPNAME
}


start() {
	printf "${YELLOW}Loading module: %s\n${ENDCOLOR}" $MODULE 
	insmod ./$MODULE.ko $* || exit 1
	MAJOR=$(awk -v mod=$MODULE '{if ($2 == mod) { print $1 }}' /proc/devices)
	if [ "$MAJOR" == "" ]
	then
		printf "error: %s: Module %s does not exist in /proc/devices\n" $APPNAME $DEVICE
		exit 0
	fi
	printf "Major number of device: %d\n" $MAJOR
	printf "Creating device node: %s\n" "/dev/${DEVICE}"	
	mknod "/dev/${DEVICE}" c $MAJOR $MINOR
	chown $DEV_USER:$DEV_GROUP "/dev/${DEVICE}"
	chmod $MODE "/dev/${DEVICE}"
#	for ((i=0 ; i < $COUNTER ; i++))
#	do
#		printf "Creating device node: %s\n" "/dev/${DEVICE}${i}"	
#		mknod "/dev/${DEVICE}${i}" c $MAJOR $i
#		chown $DEV_USER:$DEV_GROUP "/dev/${DEVICE}${i}"
#		chmod $MODE "/dev/${DEVICE}${i}"
#	done	
}

stop() {

	printf "${YELLOW}Unloading module: %s\n${ENDCOLOR}" $MODULE
	printf "Removing device node: %s\n" "/dev/${DEVICE}"	
	rm -f "/dev/${DEVICE}"
#	for ((i=0 ; i < $COUNTER ; i++))
#	do
#		printf "Removing device node: %s\n" "/dev/${DEVICE}${i}"	
#		rm -f "/dev/${DEVICE}${i}"
#	done	
	rmmod $MODULE
}

if [ "$USER" != "root" ]
then
	printf "${RED}error: %s: You must be root!\n${ENDCOLOR}" $APPNAME
	exit 0
fi

OPERATION=$1
shift

case $OPERATION in 
	"start")
		start $*
		;;
	"stop")
		stop	
		;;
	"restart")
		stop
		start $*
		;;
	*)
		usage
		exit 0
		;;
esac
